#include "SocketComm.h"

SocketComm::SocketComm(void):SocketComm_base()
{
}


SocketComm::~SocketComm(void)
{
	WSACleanup();
}


int SocketComm::Open(char *ipAddress, int SockPort)
{
	system("cls");

	// SOCKET INITIALIZATION
	if(WSAStartup(MAKEWORD(2,0),&wsaData) != 0)
	{
		cout<<"Socket Initialization Error.\n";
		return -1;;
	}

	lhSocket = socket(AF_INET,SOCK_STREAM,0);

	if(lhSocket == INVALID_SOCKET)
	{
		cout<<"Invalid Socket "<<GetLastError()<<". Program Aborted\n"<<endl;
		return -1;
	}

	// RESOLVING PROVIDED HOST NAME
	myHost = gethostbyname(ipAddress);
	
	if(myHost == 0)
	{
		cout<<"HOST NOT FOUND: "<<ipAddress<<endl;
		return -1;
	}

	cout<<"Connecting to Address: "<<ipAddress<<endl;
	
	memset(&lSockAddr,0, sizeof(lSockAddr));
	lSockAddr.sin_family = AF_INET;
	lSockAddr.sin_port = htons(SockPort);
	lSockAddr.sin_addr.s_addr = *((unsigned long*)myHost->h_addr);

	return 1;
}

void SocketComm::Connect(void)
{
	if(connect(lhSocket,(SOCKADDR *)&lSockAddr,sizeof(SOCKADDR_IN)))
	{
		cout<<"Connect Error. Program aborted\n";
	}
	else
	{
		cout<<"Connection with Host -> ESTABILISHED.\n";
	}

}

int SocketComm::SendData(BCIMessage *myDataOut)
{
	if (send(lhSocket,(char*)myDataOut,sizeof(BCIMessage),0))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void SocketComm::Close(void)
{
	closesocket(lhSocket);
	cout<<"Closing Socket Connection\n";
	WSACleanup();
}

int SocketComm::RecvData(BCIMessage *myDataIn)
{
	int iResult;

	iResult = recv(lhSocket, (char*)myDataIn, sizeof(BCIMessage), 0);
	if ( iResult <= 0 )
	{
		Sleep(16);
	}

	return iResult;
}